# utils/driver.py
from appium import webdriver
from appium.options.common import AppiumOptions
from utils.logger import Logger
import time
from config.config import Config
from utils.time_recorder import time_record

class Driver:

    def __init__(self):
        self.logger = Logger().get_logger()
        self.driver = None
        self._initialized = False


    def get_driver(self) -> webdriver.Remote:
        if not self._initialized:
            self.driver = self._init_driver()
            self._initialized = True
        return self.driver


    def _init_driver(self) -> webdriver.Remote:
        max_retries = 3
        retry_count = 0
        while retry_count < max_retries:
            try:
                options = AppiumOptions()
                options.load_capabilities(Config.capabilities)
                self.driver = webdriver.Remote(
                    command_executor=Config.command_executor,
                    options=options
                )
                self.logger.info("驱动初始化成功")
                return self.driver
            except Exception as e:
                retry_count += 1
                self.logger.info(f"驱动初始化失败，第 {retry_count} 次重试，错误: {str(e)}")
                if retry_count < max_retries:
                    time.sleep(3)
        raise RuntimeError("驱动初始化失败，已重试 3 次")


    def quit(self):
        """退出驱动"""
        if self.driver:
            try:
                self.driver.quit()
                self.logger.info("退出驱动")
            except Exception as e:
                self.logger.error(f"退出驱动时出错: {e}")
            finally:
                self.driver = None
                self._initialized = False